package cn.bdqn.brand.controller;

import cn.bdqn.brand.pojo.Brand;
import cn.bdqn.brand.service.BrandService;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "AddBrandServlet",urlPatterns = "/AddBrandServlet")
public class AddBrandServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 编码格式
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        BufferedReader reader = request.getReader();
        String jsonData = reader.readLine();

        Brand brand = JSON.parseObject(jsonData, Brand.class);
        // 将获取到的参数封装成对象

        // 调用service
        BrandService service = new BrandService();
        boolean rs = service.addBrand(brand);

        // {code: 200,msg:'删除成功'}
        Map<String,Object> data = new HashMap<>();

        if (rs){
            data.put("code","200");
            data.put("msg","添加成功！");
        }else{
            data.put("code","201");
            data.put("msg","添加成功！请练习管理员！");
        }

        // 转换成json
        String json = JSON.toJSONString(data);

        response.setContentType("application/json");
        response.getWriter().write(json);

    }
}
